import java.util.Random;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 17655
 * Date: 2024-11-28
 * Time: 14:35
 */
// 快速排序
// 优化：如何选择key值
// 用随机的方式选择基准元素
public class test2 {
    /*
    LeetCode 912 排序数组
    给你一个整数数组 nums，请你将该数组升序排列。
     */

    public int[] sortArray(int[] nums) {
        qsort(nums,0,nums.length-1);
        return nums;

    }

    public void qsort(int []nums,int l,int r){
        if(l>=r){
            return;
        }
        int key = nums[new Random().nextInt(r-l+1)+l];
        int left = l-1;
        int right = r+1;
        int i = l;
        while(i<right){
            if(nums[i]<key){
                swap(nums,++left,i++);
            }else if(nums[i]==key){
                i++;
            }else{
                swap(nums,--right,i);
            }
        }

        qsort(nums,l,left);
        qsort(nums,right,r);
    }

    public void swap(int []nums,int right,int left){
        int tmp = nums[left];
        nums[left] = nums[right];
        nums[right] = tmp;
    }
}
